package com.dhcc.bpm.common.docNode;

import java.util.List;

/**
 * @ClassName ForestDocNodeMerge
 * @Description 文档节点
 * @Author sjm
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
public class ForestDocNodeMerge {

    /**
     * 将节点数组归并为一个森林（多棵树）（填充节点的children域）
     * 时间复杂度为O(n^2)
     *
     * @param items 节点域
     * @return 多棵树的根节点集合
     */
    public static <T extends ZtreeNode> List<T>  merge(List<T> items) {
        ForestDocNodeManger<T> forestDocNodeManager = new ForestDocNodeManger<>(items);
        items.forEach(forestDocNode -> {
            if (!"0".equals(forestDocNode.getParentId())) {
                ZtreeNode treeNodeAT = forestDocNodeManager.getTreeNodeAT(forestDocNode.getParentId());
                if (treeNodeAT != null) {
                    treeNodeAT.getChildren().add(forestDocNode);
                } else {
                    forestDocNodeManager.addParentId(forestDocNode.getCode());
                }
            }
        });
        return forestDocNodeManager.getRoot();
    }
}
